/*
 * @Author: WangYuncheng
 * @Date: 2022-12-20 13:30:16
 * @LastEditors: WangYuncheng
 * @LastEditTime: 2023-02-02 13:31:11
 * @Description: 文件说明
 */
import axios from 'axios'
import { userStore } from '@/store/user.js'
import settle from 'axios/lib/core/settle'
import buildURL from 'axios/lib/helpers/buildURL'

const httpRequest = axios.create({
  baseURL: import.meta.env.DEV ? import.meta.env.VITE_DEV_BASE_URL : import.meta.env.VITE_PROD_BASE_URL,
  // baseURL: 'http://localhost:9090',
  timeout: 30000,
  headers: {
    'Content-Type': 'application/x-www-form-urlencoded',
    'X-Requested-With': 'XMLHttpRequest',
    'Access-Control-Allow-Origin': '*'
  }
})

httpRequest.defaults.adapter = (config) => {
  return new Promise((resolve, reject) => {
    uni.request({
      method: config.method.toUpperCase(),
      url: config.baseURL + buildURL(config.url, config.params, config.paramsSerializer),
      header: config.headers,
      params: config.params,
      data: config.data ? JSON.parse(config.data) : '',
      dataType: config.dataType,
      responseType: config.responseType,
      sslVerify: config.sslVerify,
      complete: function complete(response) {
        // console.log("执行完成：", response)
        response = {
          data: response.data,
          status: response.statusCode,
          errMsg: response.errMsg,
          header: response.header,
          config: config
        }
        settle(resolve, reject, response)
      }
    })
  })
}

httpRequest.interceptors.request.use(
  async (config) => {
    uni.$emit('showLoading')
    const useUserStore = userStore()
    config.headers['Token'] = useUserStore.token
    return config
  },
  (err) => {
    uni.showToast({
      icon: 'error',
      title: '请求被拒绝或网络出错'
    })
    return Promise.reject(err)
  }
)

httpRequest.interceptors.response.use(
  async (res) => {
    uni.$emit('hideLoading')
    return res.data
  },
  async (err) => {
    uni.$emit('hideLoading')
    if (err.response) {
      if (err.response.status === 401) {
        uni.reLaunch({
          url: '/pages/login/login'
        })
      }
      uni.showToast({
        icon: 'error',
        title: err.response.data.message
      })
    } else {
      uni.showToast({
        icon: 'error',
        title: '请求被拒绝或网络出错'
      })
    }
    return Promise.reject(err)
  }
)

export default httpRequest
